from django.conf import settings
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from goods.models import SKU, Catalog, SPU, SKUImage, SPUSaleAttr, SaleAttrValue, SKUSpecValue
from utils.cache_dec import cache_check


# Create your views here.

class GoodsIndexView(View):
    def get(self, request):
        """
            首页视图展示逻辑
            {
                "code":200,
                "data":[
                    {},{},{},{}
                ]
            }
        """
        data = []
        all_catalog = Catalog.objects.all()
        for cata in all_catalog:
            cata_dict = {}
            cata_dict['catalog_id'] = cata.id
            cata_dict['catalog_name'] = cata.name
            spu_ids = SPU.objects.filter(catalog=cata).values("id")
            sku_list = SKU.objects.filter(spu__in=spu_ids)
            sku = []
            for one_sku in sku_list:
                d = {
                    "skuid": one_sku.id,
                    "caption": one_sku.caption,
                    "name": one_sku.name,
                    "price": one_sku.price,
                    "image": str(one_sku.default_image_url)
                }
                sku.append(d)
            cata_dict["sku"] = sku
            data.append(cata_dict)
        results = {
            "code": 200,
            "data": data,
            "base_url": settings.PIC_URL
        }
        return JsonResponse(results)


class GoodsDetailView(View):
    @cache_check(key_prefix="gd", key_param="sku_id", cache="goods_detail", expire=300)
    def get(self, request, sku_id):
        """
            详情页展示视图逻辑
            {"code": xxx, "data": {} ,"base_url":xxxx}
            #响应示例
# {"code":200, "data":{}, "base_url":xxx}
{
    "code": 200,
    "data": {
        # 类1:类别id 类别name
        "catalog_id": 1,
        "catalog_name": "手提包",

        # 类2：SKU
        "name": "手提包",
        "caption": "最时尚的手提包",
        "price": "12345.00",
        "image": "1.png",
        "spu": 2,

        # 类3：详情图片
        "detail_image": "v2-1.jpg",

        
    },
    "base_url": "http://127.0.0.1:8000/media/"
}
        """
        try:
            sku_item = SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({"code": 10300, "error": "没有该商品"})
        data = {}
        sku_catelog = sku_item.spu.catalog
        data["catalog_id"] = sku_catelog.id
        data["catalog_name"] = sku_catelog.name
        data["name"] = sku_item.name
        data["caption"] = sku_item.caption
        data["price"] = sku_item.price
        data['image'] = str(sku_item.default_image_url)
        data["spu"] = sku_item.spu.id
        # 详情图片
        img_query = SKUImage.objects.filter(sku=sku_item)
        if img_query:
            data["detail_image"] = img_query[0]
        else:
            data["detail_image"] = ""
        # 销售属性值的id列表和name列表
        attr_value_query = sku_item.sale_attr_value.all()
        data["sku_sale_attr_val_id"] = [i.id for i in attr_value_query]
        data['sku_sale_attr_val_names'] = [i.name for i in attr_value_query]
        # 销售属性名的id列表和name列表
        attr_name_query = SPUSaleAttr.objects.filter(spu=sku_item.spu)
        data["sku_sale_attr_id"] = [i.id for i in attr_name_query]
        data['sku_sale_attr_names'] = [i.name for i in attr_name_query]
        # 销售属性 和销售属性值的关系
        """
            # 类4：销售属性
            "sku_sale_attr_id": [7,8]
            "sku_sale_attr_names": ["尺寸","颜色"],

            # 类5：销售属性值
            "sku_sale_attr_val_id": [11,12,13]
            "sku_sale_attr_val_names": ["18寸","19寸","蓝色"],

            # 销售属性和销售属性值的对应关系
            "sku_all_sale_attr_vals_id": {
                "7": [11,12],
                "8": [13]
            },
            "sku_all_sale_attr_vals_name": {
                "7": ["18寸","19寸"],
                "8": ["蓝色"]
            },
        """
        sku_all_sale_attr_vals_id = {}
        sku_all_sale_attr_vals_name = {}
        for id in data['sku_sale_attr_id']:
            sku_all_sale_attr_vals_id[id] = []
            sku_all_sale_attr_vals_name[id] = []
            item_query = SaleAttrValue.objects.filter(spu_sale_attr=id)
            for item in item_query:
                sku_all_sale_attr_vals_id[id].append(item.id)
                sku_all_sale_attr_vals_name[id].append(item.name)
        data['sku_all_sale_attr_vals_id'] = sku_all_sale_attr_vals_id
        data['sku_all_sale_attr_vals_name'] = sku_all_sale_attr_vals_name
        """
            # 类6和类7：规格属性名和规格属性值
            "spec": {
                "批次": "2000",
                "数量": "2000",
                "年份": "2000"
            }
        """
        spec = {}
        spec_query = SKUSpecValue.objects.filter(sku=sku_item)
        for spec_obj in spec_query:
            value = spec_obj.name
            key = spec_obj.spu_spec.name
            spec[key] = value
        data['spec'] = spec
        result = {"code": 200, "data": data, "base_url": settings.PIC_URL}
        return JsonResponse(result)
